package com.jds.test.proxy;

import java.io.*;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by sunyuming on 18/10/16.
 */
public class ProxyServer {

    public static void main(String[] args) throws InterruptedException {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        Runnable runnable = new LoadProperty();
        scheduledThreadPoolExecutor.scheduleAtFixedRate(runnable, 0, 60, TimeUnit.SECONDS);

    }

    private static class LoadProperty implements Runnable {

        private static Set<String> lastPropertySet = new HashSet<>();

        @Override
        public void run() {
            System.out.println("开始读取配置");

            Set<String> thisTime = null;

            try {
                thisTime = readProperties();
            } catch (Exception e) {
                e.printStackTrace();
            }

            Set<String> delSet = getFormer(lastPropertySet, thisTime);
            for(String item : delSet) {
                System.out.println("***************去除信任服务" + item);
                Client4Reconnect.interrupt(item);
            }

            Set<String> newSet = getFormer(thisTime, lastPropertySet);
            for(String item : newSet) {
                System.out.println("***************新增信任服务" + item);
                Client4Reconnect.create(item);
            }

            lastPropertySet = thisTime;

            System.out.println("结束读取配置");
        }
    }

    private static Set<String> readProperties() throws Exception {
        InputStreamReader read = null;
        Set<String> set = new HashSet<>();
        try {
            String encoding = "UTF-8";
            File file = new File("servers.config");
            if (file.isFile() && file.exists()) {
                read = new InputStreamReader(new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    set.add(lineTxt);
                }
            } else {
                throw new Exception("找不到指定的文件");
            }
            return set;
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            read.close();
        }
    }

    /**
     * 返回前者set独有的
     * @param former
     * @param batter
     * @return
     */
    private static Set<String> getFormer(Set<String> former, Set<String> batter) {
        Set<String> set = new HashSet<>();
        for(String item : former) {
            if(!batter.contains(item)) {
                set.add(item);
            }
        }
        return set;
    }

}
